// vk.com - task 5
// Dictionary lookup
// lookup.c

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "lookup.h"

static char substring_is_found = 0;
static unsigned long dict_offset = 0;
static unsigned long blocksize = 256;
static char dict_filename[255];
static char substring[255];


void Lookup_SetDictFilename(const char *dict_name) {
	strcpy(dict_filename, dict_name);
}

void Lookup_SetSubstring(const char *subs) {
	strcpy(substring, subs);
}

void Lookup_SetBlockSize(const unsigned long bsize) {
	blocksize = (bsize < MAX_BUFFER_SIZE) ? bsize : MAX_BUFFER_SIZE;
}

char Lookup_IsSuccessful(void) {
	return substring_is_found;
}

void Lookup_Reset(void) {
	substring_is_found = 0;
	dict_offset = 0;
}


void *Lookup_Thread(void *arg) {
char *buffer;
char *pres;
FILE *dict;
unsigned long current_offset;

	buffer = (char*)malloc(blocksize+1);
	if (buffer) {
		dict = fopen(dict_filename, "r");
		
		while (!substring_is_found) {
			current_offset = dict_offset;
			dict_offset += blocksize - (strlen(substring)-1);
			fseek(dict, current_offset, SEEK_SET);
	
			if (!fread(buffer, 1, blocksize, dict)) break;
			buffer[blocksize] = '\0';
			pres = strstr(buffer, substring);
			if (pres) {
				substring_is_found = 1;
				break;
			}
		}
		fclose(dict);
		free (buffer);
	}
	return NULL;
}
